package com.umessage.common.shiro;

import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;

import com.alibaba.fastjson.JSONObject;
import com.umessage.common.service.RedisService;
import com.umessage.hotel.domain.WxCfg;
import com.umessage.hotel.service.WxCfgService;
import com.umessage.hotel.util.HotelConstant;
import com.umessage.hotel.util.HttpUtil;
import com.umessage.system.service.UserService;

/* *
 * @Author tomsun28
 * @Description 
 * @Date 18:07 2018/3/3
 */
public class JwtRealm extends AuthorizingRealm {

	@Autowired
	private RedisService redisService;
	@Autowired
	private UserService userService;
	@Autowired
	private WxCfgService wxCfgService;
	
	public Class<?> getAuthenticationTokenClass() {
		// 此realm只支持jwtToken
		return JwtToken.class;
	}

	@Override
	protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {

//		SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
//		info.addStringPermission("hotel:get");

		return null;
	}

	@Override
	protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken)
			throws AuthenticationException {
		if (!(authenticationToken instanceof JwtToken)) {
			return null;
		}
		JwtToken jwtToken = (JwtToken) authenticationToken;
		
		WxCfg wxCfg = wxCfgService.queryWxCfg("10044", "2");// 酒店端
		// 验证code
		JSONObject userInfo = HttpUtil.getWXUserInfo((String) jwtToken.getCode(), wxCfg);
		String openid = userInfo.getString("openid");
		if (openid == null) {
			throw new AuthenticationException("invalid code");
		}

		if(!"wxxq".equals(jwtToken.getVercode())) {
			String key = HotelConstant.VERCODE_PREFIX + "_" + HotelConstant.VERCODE_TYPE_HOTEL + "_" + jwtToken.getMobile();
			String vc = (String) redisService.get(key);
			if (vc == null) {
				throw new AuthenticationException("unexist vercode");
			}
			
			if (!vc.equals(jwtToken.getVercode())) {
				throw new AuthenticationException("invalid vercode");
			}
		}

		return new SimpleAuthenticationInfo(openid, jwtToken.getCredentials(), this.getName());
	}
}
